package cn.han.io;

import java.io.*;
import java.util.Scanner;

//本类用于完成文件复制案例
//1.拿到源文件的路径
//2.拿到目标位置的路径
//3.调用方法完成文件的复制
public class TestCopyFile {
    public static void main(String[] args) {
        //1.提示并接收用户输入的路径
        System.out.println("请输入源文件的路径");
        String f = new Scanner(System.in).nextLine();
        System.out.println("请输入目标位置的路径（含文件名）：");
        String t = new Scanner(System.in).nextLine();
        //2.根据这两个路径调用自定义方法
//        ZFCopy(f, t);//用字符流完成文件复制的功能
        ZJCopy(f,t);//用字节流完成文件复制的功能

    }

    private static void ZJCopy(String f, String t) {
        InputStream in = null;
        OutputStream os = null;

        try {
            in = new BufferedInputStream(new FileInputStream(f));


            os = new BufferedOutputStream(new FileOutputStream(t));
            int b;
            while ((b = in.read()) != -1) {
                os.write(b);
            }
            System.out.println("恭喜您！复制成功");

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    private static void ZFCopy(String f, String t) {
        Reader r = null;
        Writer w = null;

        try {
            r = new BufferedReader(new FileReader(f));
            w = new BufferedWriter(new FileWriter(t));
            int b;
            while ((b = r.read()) != -1) {
                w.write(b);
            }
            System.out.println("恭喜您！复制成功");

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                w.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                r.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }


}
